<script setup lang="ts">
import { useRouter } from 'vue-router';
import consts from '@/consts.ts';
import { uploadPost } from '@/services/index.ts';
import { addQualificationPost, informationGet, updateQualificationPost } from '@/services/my.ts';
import type { CertificateList } from '@/types/my.ts';

const $router = useRouter();
const certiForm = ref();
const active = ref('BUSINESS_LICENSE');
const certificateData: {
  certificateList: CertificateList[];
} = reactive({
  certificateList: [],
});
const activeForm = ref<Partial<CertificateList>>({});
const rules: any = reactive({
  effectiveDate: [{ required: true, message: '请选择证件生效日期' }],
  expiredDate: [{ required: true, message: '请选择证件失效日期' }],
  qualificationCode: [{ required: true, message: '请输入证件编号' }],
  qualificationImg: [{ required: true, message: '请上传证件照' }],
});

const onClickTab = () => {
  loadData();
};
const onSubmitClick = async () => {
  try {
    await certiForm.value.validate();
    const params = {
      customerQualificationId: activeForm.value.customerQualificationId,
      effectiveDate: activeForm.value.effectiveDate,
      expiredDate: activeForm.value.expiredDate,
      qualificationCode: activeForm.value.qualificationCode,
      qualificationImg: activeForm.value.qualificationImg?.[0]?.url ?? undefined,
      qualificationType: activeForm.value.qualificationType,
    };
    const { err, message } = params.customerQualificationId
      ? await updateQualificationPost(params)
      : await addQualificationPost(params);
    if (err) {
      showToast(err);
      return;
    }
    showToast(message);
  } catch (errors) {
    console.log('表单验证失败', errors);
  }
};
const beforeRead = (file: any) => {
  const isJPG =
    file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
  const isLt1M = file.size / 1024 / 1024 < 10;
  if (!isJPG) {
    showToast('只能上传jpg/png/jpeg文件!');
  }
  if (!isLt1M) {
    showToast('上传图片大小不能超过 10MB!');
  }
  return isJPG && isLt1M;
};
// 上传图片处理
const afterRead = async (file: any, type: string) => {
  file.status = 'uploading';
  file.message = '上传中...';
  const formData = new FormData();
  formData.append('file', file.file);
  const { err, data } = await uploadPost(formData);
  if (err) {
    file.status = 'failed';
    file.message = '上传失败';
  } else {
    file.status = 'done';
    file.message = '上传成功';
  }
  activeForm.value[type] = [{ url: data }];
};
// 时间选择器
const showPicker = ref(false);
const selectPick = ref('');
const maxDate = ref(new Date(2050, 5, 1));
const onShowPickClick = (type: string) => {
  showPicker.value = true;
  selectPick.value = type;
};

const showPreview = ref(false);
const previewImages = ref<string[]>([]);
const onImagePreview = () => {
  showPreview.value = true;
  previewImages.value = activeForm.value.qualificationImg?.map((item: any) => item.url || '') || [];
};
const onConfirm = ({ selectedValues }: { selectedValues: string[] }) => {
  activeForm.value[selectPick.value] = selectedValues.join('/');
  showPicker.value = false;
};
const loadData = async () => {
  const { err, data } = await informationGet();
  if (err) {
    showToast(err);
    return;
  }
  certificateData.certificateList = data.customerQualificationList;
  const findActive = data.customerQualificationList.find(
    (item: any) => item.qualificationType === active.value,
  );
  if (findActive) {
    activeForm.value = {
      ...findActive,
      qualificationImg: findActive.qualificationImg ? [{ url: findActive.qualificationImg }] : [],
    };
  } else {
    activeForm.value = {};
  }
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="certificate-container">
    <van-tabs
      v-model:active="active"
      @click-tab="onClickTab"
      line-width="1.2em"
      color="#E89000"
      title-active-color="#00BA9F"
      :ellipsis="false"
    >
      <van-tab
        v-for="(item, index) in consts.qualificationType"
        :name="item.qualificationType"
        :title="item.title"
        :key="index"
      >
      </van-tab>
      <div class="certificate-box">
        <van-form required="auto" :rules="rules" ref="certiForm" label-width="7em">
          <div v-if="activeForm.qualificationImg" class="upload-field">
            <van-uploader
              v-model="activeForm.qualificationImg"
              :deletable="false"
              reupload
              :before-read="beforeRead"
              :after-read="(file: any) => afterRead(file, 'qualificationImg')"
              :max-count="1"
            >
              <template #default>
                <div class="upload-style">
                  <svg-icon icon-class="uploader" size="1.4em" />
                </div>
              </template>
            </van-uploader>
            <div @click="onImagePreview" class="upload-field-title">查看大图</div>
          </div>
          <van-field
            v-else
            :rules="rules.qualificationImg"
            name="qualificationImg"
            label="证件照片"
          >
            <template #input>
              <van-uploader
                v-model="activeForm.qualificationImg"
                :before-read="beforeRead"
                :after-read="(file: any) => afterRead(file, 'qualificationImg')"
                :max-count="1"
              >
                <template #default>
                  <div class="upload-style">
                    <svg-icon icon-class="uploader" size="1.4em" />
                  </div>
                </template>
              </van-uploader>
            </template>
          </van-field>
          <div class="inputSpace">
            <van-field
              readonly
              label="证件生效日期"
              :rules="rules.effectiveDate"
              v-model="activeForm.effectiveDate"
              name="effectiveDate"
              placeholder="点击选择证件生效日期"
              @click="onShowPickClick('effectiveDate')"
            />
            <van-field
              readonly
              label="证件失效日期"
              :rules="rules.expiredDate"
              v-model="activeForm.expiredDate"
              name="expiredDate"
              placeholder="点击选择证件失效日期"
              @click="onShowPickClick('expiredDate')"
            />
            <!-- :rules="rules.qualificationCode" -->
            <van-field
              label="证件编号"
              v-model="activeForm.qualificationCode"
              name="qualificationCode"
              placeholder="请输入证件编号"
            />
          </div>
          <div class="user-bottom">
            <van-button @click="onSubmitClick" color="#E89000" round block>
              保存并提交审核
            </van-button>
            <van-button @click="$router.go(-1)" color="#E89000" plain round block>
              返回
            </van-button>
          </div>
        </van-form>
      </div>
    </van-tabs>
  </div>
  <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
    <van-date-picker :max-date="maxDate" @confirm="onConfirm" @cancel="showPicker = false" />
  </van-popup>
  <van-image-preview v-model:show="showPreview" :images="previewImages"></van-image-preview>
</template>

<style scoped lang="scss">
.upload-field {
  width: 100%;
  height: 272px;
  flex-direction: column;
  display: flex;
  align-items: center;
  justify-content: center;

  :deep(.van-image) {
    width: 170px;
    height: 240px;
  }

  .upload-field-title {
    color: #00ba9f;
    font-size: 12px;
    font-weight: 400;
    text-decoration-line: underline;
  }
}

.certificate-container {
  width: 100%;
  min-height: 100vh;

  .certificate-box {
    width: 100%;
    height: 272px;
    padding: 0 16px;

    .van-cell {
      padding-right: 0;
      padding-left: 0;
    }

    .box-img {
      width: 100%;
      padding: 16px 0;
      display: flex;
      align-items: center;
      justify-content: center;

      .van-image {
        width: 170px;
        height: 240px;
      }
    }

    .user-bottom {
      width: 100%;
      margin: 20px 0;

      .van-button {
        margin: 10px 0;
        height: 40px;
      }
    }
  }
}
</style>
